package com.witframework.util;

import java.util.zip.Adler32;


public class IdGenerator {
	public static String HEXNUMBE="0123456789abcdef";
	/**
	 * 根据32为长度的16基数表示的UUID获得一个long值
	 * 该long值并不能唯一对应到一个UUID值。此方法的实现仅仅是为了加快数据的
	 * 检索效率和弥补因为另一个保存真正的UUID值的信息丢失。
	 * @param uuid
	 * @return long
	 */
	public static long toLong(String uuid){
		try{
			return Long.parseLong(uuid);
		}catch(Exception e){}
		if(uuid==null) return 0;
		uuid="00000000000000000000000000000000"+uuid;
		for(int i=0;i<uuid.length();i++){
			if(HEXNUMBE.indexOf(uuid.charAt(i))<0){
				int index=(int)uuid.charAt(i)%15;				
				uuid=uuid.replace(uuid.charAt(i), HEXNUMBE.charAt(index));
			}
		}		
		String hashCode=String.valueOf(Math.abs(uuid.hashCode()));
		String endString=uuid.substring(uuid.length()-2);
		String preString;
		if(hashCode.length()>6)
			preString=hashCode.substring(hashCode.length()-6)+endString.substring(endString.length()-2);	
		else
			preString=hashCode.substring(hashCode.length())+endString.substring(endString.length()-2);
		
		Adler32 adler32=new Adler32();
		adler32.update(uuid.getBytes());	
		String crc="00000000000"+adler32.getValue();
		String result="00000000000000000000000000000000"+Long.parseLong(preString,16)+crc.substring(crc.length()-10);
		return Long.parseLong(result.substring(result.length()-18));
		
	}	
	public static String UUID(){		
		StringBuffer s=new StringBuffer(32);
		s.append(new java.text.SimpleDateFormat( "yyyyMMddHHmmss" ).format( java.util.Calendar.getInstance().getTime()));
		s.append(fz(new java.rmi.server.UID().toString().replace("-","").replace(":","")));	
		s.append(Math.abs(new java.util.Random().nextInt()));
		return s.toString().substring(0,32);
	}
	public static String generateId(String source){
		String a=new java.text.SimpleDateFormat( "yyyyMMddHHmmss" ).format( java.util.Calendar.getInstance().getTime() );
		return a+toLong(source);
	}
	public static String UUID(int length){			
		if(length<=18){
			length=18;			
		}else if(length>32){
			length=32;
		}
		return UUID().substring(0,length);
	}
	private static String fz(String source){
		byte[] s=source.getBytes();
		byte[] d=new byte[s.length];
		for(int i=s.length-1;i>=0;i--){
			d[d.length-i-1]=s[i];
		}
		return new String(d);
	}
	public static void main(String[] s){
		System.out.println(generateId("2"));
		System.out.println(toLong("你好"));
		java.util.List l=new java.util.ArrayList();
		for(int i=0;i<1000;i++){			
			String ss=UUID(15);
			System.out.println(ss);
			if(l.contains(ss))
				System.out.println(".............."+ss);
			else{				
				l.add(ss);
			}		
		}		
	}
}
